package com.kedll.library.util;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.text.Selection;
import android.text.Spannable;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.kedll.library.KBaseApplication;


public class UIUtil {

    public static Context getContext() {
        return KBaseApplication.getContext();
    }

    //获取字符串
    public static String getString(int id) {
        return getContext().getResources().getString(id);
    }

    //获取字符串数组
    public static String[] getStringArray(int id) {
        return getContext().getResources().getStringArray(id);
    }

    //获取图片
    public static Drawable getDrawable(int id) {
        return ContextCompat.getDrawable(getContext(), id);
    }

    //获取颜色
    public static int getColor(int id) {
        return ContextCompat.getColor(getContext(), id);
    }

    //dip和px转换
    public static int dip2px(float dip) {
        float density = getContext().getResources().getDisplayMetrics().density;
        return (int) (dip * density + 0.5f);
    }


    //sp转px
    public static float sp2px(float spValue) {
        //系统Api自带转换
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, spValue, getContext().getResources().getDisplayMetrics());
    }

    

    //EditText获取焦点弹出软键盘,如果有内容把光标移动到字符串之后
    public static void setCharSequence(EditText etAccount) {
        etAccount.setFocusable(true);
        etAccount.setFocusableInTouchMode(true);
        etAccount.requestFocus();
        CharSequence charSequence = etAccount.getText();
        if (charSequence != null) {
            Spannable spanText = (Spannable) charSequence;
            Selection.setSelection(spanText,
                    charSequence.length());
        }

        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.showSoftInput(etAccount, 0);
        }
    }

    //隐藏
    public static boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = { 0, 0 };
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
}
